// pages/login/login.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    loginForm: {
      username: '',
      password: '',
      allow: true
    },
    registerForm: {
      email: '',
      code: ''
    },
    backArr: [{
      size: 100,
      back: "background-image: linear-gradient(120deg, #a6c0fe 0%, #f68084 100%);",
      bottom: "10%",
      left: "10%"
    }, ],
    select: "login"
  },
  code() {
    const registerForm = this.data.registerForm
    if (registerForm.email.length == 0) {
      this.cShowModel('小程序请求', '请先输入邮箱')
      return
    }
    let verify = /\w[-\w.+]*@([A-Za-z0-9][-A-Za-z0-9]+\.)+[A-Za-z]{2,14}/
    if (!verify.test(registerForm.email)) {
      this.cShowModel('小程序请求', '请输入正确邮箱的格式')
      return
    }
    let host = getApp().data.serverHost
    wx.request({
      url: host + "/api/auth/ask-code?" + "email=" + registerForm.email + "&type=register",
      method: "GET",
      success: (e) => {
        let data = e.data
        if (data.code == 200) {
          this.cShowModel('小程序提示', '验证码已发送，有效时间为三分钟')
        } else {
          this.cShowModel('小程序请求', data.massage)
        }
      },
      fail: () => {
        wx.showToast({
          title: '网络请求有误，请稍后再试',
          icon: "error"
        })
      }
    })
  },
  register() {
    const registerForm = this.data.registerForm
    const loginForm = this.data.loginForm
    if (registerForm.email.length == 0) {
      this.cShowModel('小程序请求', '请先输入邮箱')
      return
    }
    let verify = /\w[-\w.+]*@([A-Za-z0-9][-A-Za-z0-9]+\.)+[A-Za-z]{2,14}/
    if (!verify.test(registerForm.email)) {
      this.cShowModel('小程序请求', '请输入正确邮箱的格式')
      return
    }
    if (registerForm.code.length != 6) {
      this.cShowModel('小程序请求', '验证码的长度为6')
      return
    }
    let host = getApp().data.serverHost
    wx.request({
      url: host + "/api/auth/register",
      headers: {
        'content-type': 'application/json'
      },
      method: "POST",
      data: {
        "email": registerForm.email,
        "code": registerForm.code,
        "username": loginForm.username,
        "password": loginForm.password
      },
      success: (e) => {
        const data = e.data
        if (data.code==200) {
          this.cShowModel('小程序提示', '注册成功')
          this.setData({
            select: "login"
          })
        }else{
          this.cShowModel('小程序请求',data.massage)
        }
      },
      fail: (e) => {
        wx.showToast({
          title: '网络请求有误，请稍后再试',
          icon: "error"
        })
      }
    })
  },
  cShowModel(title, content) {
    wx.showModal({
      title: title,
      content: content,
      showCancel: false
    })
  },
  changeAllow(e) {
    this.setData({
      "loginForm.allow": !this.data.loginForm.allow
    })
  },
  change(e) {
    let data = e.currentTarget.dataset.data
    this.setData({
      select: data
    })
  },
  inputChange(e) {
    let type = e.currentTarget.dataset.type
    let value = e.detail.value
    if (type == "username") {
      this.setData({
        'loginForm.username': value
      })
    } else if (type == "password") {
      this.setData({
        "loginForm.password": value
      })
    } else if (type == "email") {
      this.setData({
        "registerForm.email": value
      })
    } else if (type == "code") {
      this.setData({
        "registerForm.code": value
      })
    }
  },
  showAgreement() {
    this.cShowModel("搞它小程序协议", "无")
  },
  showHelp() {
    this.cShowModel("搞它小程序帮助", "相信自己不需要如何帮助，你可以的")
  },
  login() {
    const loginForm = this.data.loginForm
    if (loginForm.allow == false) {
      this.cShowModel('小程序请求', '请先同意用户协议')
      return
    }
    if (loginForm.username.length == 0) {
      this.cShowModel('小程序请求', '请输入用户名')
      return
    }
    if (loginForm.password.length < 6 || loginForm.password.length > 20) {
      this.cShowModel('小程序请求', '密码长度在6到20之间')
      return
    }
    let host = getApp().data.serverHost
    wx.request({
      url: host + "/api/auth/login",
      method: "POST",
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      data: {
        username: loginForm.username,
        password: loginForm.password
      },
      success: (e) => {
        const response = e.data
        if (response.code == 200) {
          wx.setStorageSync('token', response.data.token)
          wx.setStorageSync('username', response.data.username)
          wx.setStorageSync('role', response.data.role)
          wx.setStorageSync('userID',response.data.id)
          wx.redirectTo({
            url: '/pages/index/index?ofLogin=0',
          })
        } else {
          this.cShowModel('登入失败', response.massage)
        }
      },
      fail: () => {
        wx.showToast({
          title: '网络请求有误，请稍后再试',
          icon: "error"
        })
      }
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    let verify = options.verify
    if (verify != null) {
      if(verify==0){
        this.cShowModel('消息', '欢迎光临')
      }else if(verify==1){
        wx.showToast({
          title: '网络请求有误，请稍后再试',
          icon: "error"
        })
      }
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    const arr = ["linear-gradient(120deg, #a6c0fe 0%, #f68084 100%);", "linear-gradient(to top, #cfd9df 0%, #e2ebf0 100%);", "linear-gradient(to top, #5ee7df 0%, #b490ca 100%);", "linear-gradient(120deg, #89f7fe 0%, #66a6ff 100%);", "linear-gradient(to right, #6a11cb 0%, #2575fc 100%);"]
    let count = Math.ceil(Math.random() * 5) + 10
    let backArr = new Array(count)
    for (let i = 0; i < backArr.length; i++) {
      backArr[i] = Object()
      let item = backArr[i]
      item.size = 100 + Math.ceil(Math.random() * 100)
      item.back = arr[Math.floor(Math.random() * arr.length)]
      item.bottom = String(Math.floor(Math.random() * 110) + 15) + '%'
      item.left = String(Math.floor(Math.random() * 110) - 10) + '%'
    }
    this.setData({
      backArr: backArr
    })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})